<template>
  <a-card>
    <h1>个人信息</h1>
    <hr />
    <br />
    <a-form
      v-bind="layout"
      :model="user"
      name="user"
      :validate-messages="validateMessages"
    >
      <a-form-item
        :name="['email']"
        label="邮箱"
        :rules="[{ type: 'email' }]"
        validateTrigger="change"
      >
        <a-input :placeholder="uservo.email" v-model:value="user.email" />
      </a-form-item>
      <a-form-item
        label="年龄"
        :name="['age']"
        :rules="[{ type: 'number', min: 0, max: 150 }]"
        validateTrigger="change"
      >
        <a-input-number :placeholder="uservo.age" v-model:value="user.age" />
      </a-form-item>
      <a-form-item
        label="自我介绍"
        validateTrigger="change"
        :rules="[{ type: 'string', min: 0, max: 200 }]"
        :name="['brief']"
      >
        <a-textarea
          rows="10"
          :placeholder="uservo.brief"
          showCount="true"
          v-model:value="user.brief"
        />
      </a-form-item>
      <a-form-item :wrapper-col="{ ...layout.wrapperCol, offset: 4 }">
        <a-button type="primary" @click="submit()">提交</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import { reactive } from "@vue/reactivity";
import userApi from "@/apis/userApi";
import { useStore } from "vuex";
import { onMounted } from "@vue/runtime-core";
export default {
  name: "InfoCard",

  setup(props, context) {
    let user = reactive({
      age: undefined,
      email: "",
      brief: "",
    });

    let uservo = reactive({
      age: undefined,
      email: "",
      brief: "",
    });

    const store = useStore();
    const access = store.state.user.info.access;

    const info = () => {
      userApi.getUserFrom(access).then((resp) => {
        let usertemp = resp.data.userfrom;

        if (uservo.brief !== usertemp.brief) {
          context.emit("update_brief", usertemp.brief);
        }
        uservo.age = usertemp.age;
        uservo.email = usertemp.email;
        uservo.brief = usertemp.brief;
      });
    };

    onMounted(() => {
      info();
    });

    const layout = {
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 16,
      },
    };

    const validateMessages = {
      types: {
        email: "这不是一个正确的${label}",
      },
      number: {
        range: "${label} 必须在${min} ~ ${max}之间",
      },
      string: {
        range: "${label} 必须在${min}字 ~ ${max}字之间",
      },
    };

    const submit = () => {
      userApi.updateUserFrom(user, access).then((resp) => {
        if(resp.code !== 200) return;
        info();
        user.age = undefined;
        user.email = "";
        user.brief = "";
      });
    };

    return {
      user,
      validateMessages,
      layout,
      uservo,
      submit,
    };
  },
};
</script>

<style scoped>
.center {
  justify-content: center;
  align-items: center;
  display: flex;
}
</style>